package esgi.stationratp.downloader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import esgi.stationratp.dal.StationDAL;
import esgi.stationratp.model.Station;

public class HttpDownload extends AsyncTask<URL, Integer, Integer> {

	private final String ratpDataUrl = "http://www.data.gouv.fr/var/download/a4cc3aae97f68aa98e8baee5e9e08cf7.csv";
	private ArrayList<Station> stations;
	private ProgressDialog progressDialog;
	private Context context;

	public ArrayList<Station> getStations() {
		return stations;
	}

	public HttpDownload(Activity _sender) {
		this.stations = new ArrayList<Station>();
		this.context = _sender;
	}

	private void downloadFile() {
		URL url = null;
		InputStream is = null;

		try {
			url = new URL(ratpDataUrl);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

		try {

			is = url.openStream();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(is));

			String line = null;
			ArrayList<String> file = new ArrayList<String>();
			int nbLine = 0;

			while ((line = reader.readLine()) != null) {
				file.add(line);
				nbLine++;
			}

			int readLine = 0;
			for (String item : file) {
				readLine++;

				String[] splitedLine = item.split("#");

				Station station = new Station();
				station.setId(Integer.parseInt(splitedLine[0]));
				station.setX(Float.parseFloat(splitedLine[1]));
				station.setY(Float.parseFloat(splitedLine[2]));
				station.setNom(splitedLine[3]);
				station.setVille(splitedLine[4]);
				station.setReseau(splitedLine[5]);

				stations.add(station);

				int progess = (int) ((readLine / (float) nbLine) * 100);

				publishProgress(progess);
			}

		} catch (IOException e) {
			Log.v("HttpDownload", e.getMessage());
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	private void saveAll() {
		StationDAL dal = new StationDAL(context);
		int updated = 0;
		int all = stations.size();

		for (Station station : stations) {

			if (dal.getStationById(station.getId()) == null) {

				dal.addNewStation(station);
			} else {
				dal.updateStation(station.getId(), station);
			}

			updated++;
			int progress = (int) ((updated / (float) all) * 100);

			publishProgress(progress);
		}
	}

	void deleteAll() {
		new StationDAL(context).deleteAll();
	}

	@Override
	protected Integer doInBackground(URL... params) {
		downloadFile();
		saveAll();
		return 1;
	}

	@Override
	protected void onPreExecute() {
		progressDialog = new ProgressDialog(context);
		progressDialog.setTitle("Veillez patienter ");
		progressDialog.setMessage("Updating data...");
		progressDialog.setCancelable(false);
		progressDialog.setMax(100);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

		progressDialog.show();

	}

	@Override
	protected void onPostExecute(Integer result) {
		progressDialog.dismiss();
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		progressDialog.setProgress(values[0]);
	}
}
